package com.wd.tech.net;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.google.gson.Gson;
import com.wd.tech.Api.Api;
import com.wd.tech.Api.ApiService;
import com.wd.tech.Api.App;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * date:2020/7/2
 * author:王成虎(13671)
 * month:七月
 * function:
 */
public class NetUtlis {

    private final ApiService apiServer;

    //构造函数
    public NetUtlis() {
        //拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //OKHTTP客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .writeTimeout(5,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                //自定义拦截器   可添加请求头
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request.Builder builder = request.newBuilder();
                        //添加请求头
                        SharedPreferences loginid = App.mContext.getSharedPreferences("loginid", Context.MODE_PRIVATE);
                        int userId = loginid.getInt("userId", 0);
                        String sessionId = loginid.getString("sessionId", "");
                        builder.addHeader("userId",userId+"");
                        builder.addHeader("sessionId",sessionId);
                        Request build = builder.build();
                        return chain.proceed(build);
                    }
                })
                .build();
        //retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.Base)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiServer = retrofit.create(ApiService.class);
    }
    //静态内部类单例模式
    private static class NetCall{
        private static NetUtlis netUtlis = new NetUtlis();
    }

    public static NetUtlis getInstance() {
        return NetCall.netUtlis;
    }
    //接口回调
    public interface  NetCallBack<T>{
        void onSucces(T t);
        void onError(String error);
    }
    //网络判断
    public boolean isWang(){
        ConnectivityManager manager = (ConnectivityManager) App.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        if (activeNetworkInfo!=null&&activeNetworkInfo.isAvailable()){
            return true;
        }else {
            return false;
        }
    }

    //查询banner
    public void GetXBannerInfo(String url, final Class cls, final NetCallBack callBack){
        apiServer.GetXBannerInfo(url).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.onSucces(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //展示资讯首页
    public void GetNewsShow(String url, final Class cls, Map<String ,Object>map, final NetCallBack callBack){
        apiServer.GetNewsSh(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.onSucces(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
